package org.anderground.app.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.anderground.app.R;
import org.anderground.app.controller.newnet.NetLister;
import org.anderground.app.controller.newnet.Resource.Type;
import org.anderground.core.Logger;

import android.content.Context;
import dalvik.system.DexFile;
import dalvik.system.PathClassLoader;

/**
 * MVC's Controller class
 * 
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 * @author Ilya Shurigyn (honorik@gmail.com)
 */
public class AppController {

	private Context context;

	/**
	 * gets a list of files from the directory
	 * 
	 * @param directory
	 * @param extension
	 * 
	 * @return the list of files
	 */
	public List<String> getFilesList(String directory, String extension) {
		List<String> filesList = new ArrayList<String>();
		File dir = new File(directory);
		if (!dir.exists()) {
			dir.mkdir();
		}
		for (File file : dir.listFiles()) {
			String fn = file.getName();
			if (extension == null || fn.endsWith(extension)) {
				filesList.add(fn);
			}
		}
		return filesList;
	}

	/**
	 * gets a list of files from the maps directory
	 * 
	 * @return the list of files
	 */
	public List<String> getMapsList() {
		return getFilesList(context.getString(R.string.maps_dir), context
				.getString(R.string.maps_extension));
	}

	/**
	 * gets a list of files from the classes directory
	 * 
	 * @return the list of files
	 */
	public List<String> getPacksList() {
		return getFilesList(context.getString(R.string.drawers_dir), null);
	}

	/**
	 * lists all classes contained in the file
	 * 
	 * @param path
	 * @return
	 */
	public List<Class<?>> extractClasses(String path) {
		ArrayList<Class<?>> classList = new ArrayList<Class<?>>();
		try {
			File file = new File(path);
			DexFile dexFile = new DexFile(file);
			Enumeration<String> entries = dexFile.entries();
			Class<?> extractedClass;
			ClassLoader classLoader = new PathClassLoader(file
					.getAbsolutePath(), context.getClassLoader());
			while (entries.hasMoreElements()) {
				String element = entries.nextElement();
				try {
					extractedClass = classLoader.loadClass(element);
					classList.add(extractedClass);
					Logger.log("extracted class: " + extractedClass.getName());
				} catch (ClassNotFoundException e) {
					Logger.e("failed to extract: " + element, e);
				}
			}
			dexFile.close();

		} catch (IOException e) {
			Logger.log(e);
		}
		return classList;
	}

	public void obtainMapsFromNet(NetLister.Listener listener) {
		NetLister.update(listener, Type.MAP);
	}

	public void obtainDrawersFromNet(NetLister.Listener listener) {
		NetLister.update(listener, Type.DRAWER);
	}

}
